/*
 * Copyright (C) 2009 CityLights Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.schizoidman.android.citylights;

import java.io.IOException;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;

import com.schizoidman.android.citylights.model.TCBuildTypeProxy;
import com.schizoidman.android.citylights.model.TCProjectProxy;

public class BuildConfigsListPage extends ListActivity implements ListView.OnScrollListener  {

	private TCProjectProxy mProject;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);

		mProject = new TCProjectProxy(getIntent());
		final LazyStatusAdapter adapter = new LazyStatusAdapter();
		setListAdapter (adapter);
		getListView().setOnScrollListener(this);

		// Set custom title
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.i_title_no_button);
		setTitle(getIntent().getStringExtra(TCProjectProxy.NAME));

		// Load project from HTTP asynchronously
		new AsyncLoader() {
			@Override
			protected void load() throws ClientProtocolException, IOException,
					JSONException {
				mProject.load();
			}
			
			@Override
			public void onLoadingStarted() {
				findViewById(R.id.progress).setVisibility(View.VISIBLE);
			}

			@Override
			public void onLoadingFinished(int status, String errMessage) {
				switch (status) {
				case LOADING_FAILED:
					Toast.makeText(BuildConfigsListPage.this, errMessage, Toast.LENGTH_LONG).show();
					BuildConfigsListPage.this.finish();
				case LOADING_SUCCEDED:
					adapter.notifyDataSetChanged();
					((TextView)findViewById(R.id.title)).setText(getIntent().getStringExtra(TCProjectProxy.NAME));
					findViewById(R.id.progress).setVisibility(View.GONE);
					getListView().post(new Runnable() {
						public void run() {
							loadVisibleBuilds();
						};
					});
				}
			}
		}.asyncLoad();
	}

	/* (non-Javadoc)
	 * @see android.app.ListActivity#onListItemClick(android.widget.ListView, android.view.View, int, long)
	 */
	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		setResult(RESULT_OK, ((TCBuildTypeProxy)l.getItemAtPosition(position)).getData());
		finish();
	}

	/* (non-Javadoc)
	 * @see android.widget.AbsListView.OnScrollListener#onScroll(android.widget.AbsListView, int, int, int)
	 */
	public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
			int totalItemCount) {
	}

	/* (non-Javadoc)
	 * @see android.widget.AbsListView.OnScrollListener#onScrollStateChanged(android.widget.AbsListView, int)
	 */
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		switch (scrollState) {
		case OnScrollListener.SCROLL_STATE_IDLE:
			loadVisibleBuilds();
		}
	}
	
	/**
	 * Starts loading jobs for all builds which are currently visible on the list view
	 */
	private void loadVisibleBuilds() {
		AbsListView view = getListView();
		int count = view.getChildCount();
		for (int i=0; i<count; i++) {
			final TCBuildTypeProxy proxy = (TCBuildTypeProxy)view.getChildAt(i).getTag();
			if (proxy.getLoadingState() == TCBuildTypeProxy.LOADING_STATE_NOT_LOADED) {
				new AsyncLoader() {
					@Override
					protected void load() throws ClientProtocolException, IOException, JSONException {
						proxy.load();
					}
					@Override
					public void onLoadingFinished(int status, String errMessage) {
						View findRow = BuildConfigsListPage.this.getListView().findViewWithTag(proxy);
						Log.i("CityLights", "Find ROW: " + findRow);
						if (findRow != null) {
							updateRow(findRow);
						}
					}
					@Override
					public void onLoadingStarted() {
						View findRow = BuildConfigsListPage.this.getListView().findViewWithTag(proxy);
						Log.i("CityLights", "Find ROW: " + findRow);
						if (findRow != null) {
							updateRow(findRow);
						}
					}
				}.asyncLoad();
			}
		}
	}

	/**
	 * Updates Row view with actual values from the TCBuildTypeStub and TCBuildType
	 * @param rowm
	 */
	protected void updateRow (View row) {
		Log.i("CityLights", "updateRow : " + row.getTag());
		TextView text2 = (TextView)row.findViewById(R.id.text2);
		ImageView status = (ImageView)row.findViewById(R.id.status);
		ProgressBar progress = ((ProgressBar)row.findViewById(R.id.progress));

		TCBuildTypeProxy proxy = (TCBuildTypeProxy)row.getTag();
		if (proxy == null) {
			progress.setVisibility(View.GONE);
			text2.setText("");
		} else {
			progress.setVisibility 
			(proxy.getLoadingState() == TCBuildTypeProxy.LOADING_STATE_LOADING ? View.VISIBLE : View.GONE);
			text2.setText(proxy.getLastBuildStatusString());
			status.setImageResource(proxy.getLastBuildStatusIcon());
		}
	}

	private class LazyStatusAdapter extends BaseAdapter {
		private LayoutInflater mInflater;
		
		public LazyStatusAdapter() {
			mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public int getCount() {
			return mProject.getBuildTypes().size();
		}

		public Object getItem(int position) {
			return mProject.getBuildTypes().get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		/**
		 * Make a view to hold each row.
		 * 
		 * @see android.widget.ListAdapter#getView(int, android.view.View,
		 *      android.view.ViewGroup)
		 */
		public View getView(int position, View convertView, ViewGroup parent) {
			Log.i("CityLights", "getView(" + position + ")");

			final View row;

			if (convertView == null) {
				row = mInflater.inflate(R.layout.list_item2, parent, false);
			} else {
				row = convertView;
			}

			final TCBuildTypeProxy proxy = ((TCBuildTypeProxy)getItem(position));
			row.setTag(proxy);
			((TextView)row.findViewById(R.id.text1)).setText(proxy.toString());

			updateRow(row);
			return row;
		}
	}
}


